package com.cskaoyan.service.wxorder_service;

import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.cart.Cart;
import com.cskaoyan.bean.cart.CartExample;
import com.cskaoyan.bean.order.*;
import com.cskaoyan.bean.order.wxbean.*;
import com.cskaoyan.bean.order.wxbean.CommentBO;
import com.cskaoyan.bean.order.wxbean.OrderDetail;
import com.cskaoyan.bean.order.wxbean.submit.SubmitBO;
import com.cskaoyan.bean.order.wxbean.submit.SubmitVO;
import com.cskaoyan.bean.promotion.coupon.Coupon;
import com.cskaoyan.bean.promotion.coupon.CouponUser;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.user.UserExample;
import com.cskaoyan.mapper.*;
import com.cskaoyan.mapper.goodsMapper.MarketGoodsMapper;
import com.cskaoyan.mapper.orderMapper.MarkeChannelMapper;
import com.cskaoyan.mapper.orderMapper.MarketExpinfoMapper;
import com.cskaoyan.mapper.orderMapper.MarketOrderGoodsMapper;
import com.cskaoyan.mapper.orderMapper.MarketOrderMapper;
import com.cskaoyan.util.DateUtils;
import com.cskaoyan.util.HandleOptionUtil;
import com.cskaoyan.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Hu
 * @create 2021-09-19 11:39
 * @Description
 */

@Service
public class WXOrderServiceImpl implements WXOrderService {


    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketExpinfoMapper expinfoMapper;
    @Autowired
    MarkeChannelMapper channelMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    RegionMapper regionMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public BaseData<OrderListVO> list(BaseParam baseParam, Integer showType, Integer userid) {
        userid = 1;//---------------------------------需要替换!!!!!!
        //进行userid的配置 从shiro获得

            Subject subject = SecurityUtils.getSubject();
            String username = (String) subject.getPrincipals().getPrimaryPrincipal();
            UserExample userExample = new UserExample();
            userExample.createCriteria().andNicknameEqualTo(username);
            List<User> users = userMapper.selectByExample(userExample);
             userid = users.get(0).getId();


        List<OrderListVO> orderListVOS = new ArrayList<>();//主VO载体
        //        根据userid遍历订单     此处假设userid=1;
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userid);
        criteria.andDeletedEqualTo(false);
        //0:全部 1:待付款 2:待发货 3:待收货 4:待评价
        //default  101:待付款 201:已付款 301:已发货 401用户402系统收货
        switch (showType) {
            case 0:
                break;
            case 1:
                criteria.andOrderStatusEqualTo((short) 101);
                break;
            case 2:
                criteria.andOrderStatusEqualTo((short) 201);
                break;
            case 3:
                criteria.andOrderStatusEqualTo((short) 301);
                break;
            case 4:
                ArrayList<Short> shorts = new ArrayList<>();
                shorts.add((short) 401);
                shorts.add((short) 402);
                criteria.andOrderStatusIn(shorts);
                break;
        }
        //原始没有转VO的list数据
        List<MarketOrder> marketOrders = orderMapper.selectByExample(marketOrderExample);
        for (MarketOrder tempOrder : marketOrders) {
            OrderListVO tempOrderVO = new OrderListVO();
            //用switch赋值
            Short statusNum = tempOrder.getOrderStatus();
            //para1
            tempOrderVO.setOrderStatusText(HandleOptionUtil.getStatusString((int) statusNum));
            //param2
            tempOrderVO.setAftersaleStatus((int) tempOrder.getAftersaleStatus());
            //param3
            tempOrderVO.setIsGroupin(false);
            //para4
            tempOrderVO.setOrderSn(tempOrder.getOrderSn());
            //para5
            tempOrderVO.setActualPrice(tempOrder.getActualPrice());
            //param6
            tempOrderVO.setId(tempOrder.getId());
            //param7
            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria orderGoodsExampleCriteria = marketOrderGoodsExample.createCriteria();
            orderGoodsExampleCriteria.andOrderIdEqualTo(tempOrder.getId());
            orderGoodsExampleCriteria.andDeletedEqualTo(false);
            List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
            //重新查找个goodlist封装
            List<OrderGoodList> orderGoodLists = orderGoodsMapper.selectGoodListByOrderId(tempOrder.getId());
            tempOrderVO.setGoodsList(orderGoodLists);

            //para8
            tempOrderVO.setHandleOption(HandleOptionUtil.getHandleOptionByStatus((int) statusNum));

            orderListVOS.add(tempOrderVO);
        }

        PageUtil.start(baseParam);
        PageInfo<OrderListVO> pageInfo = new PageInfo<>(orderListVOS);
        BaseData<OrderListVO> data = new BaseData<>(pageInfo, orderListVOS);
        return data;

    }

    @Override
    public OrderDetail detail(Integer orderId) {

        OrderDetail orderDetail = new OrderDetail();


        //param1
        OrderDetailInnerInfo orderInfo = orderMapper.selectOrderDetailById(orderId);
        MarketOrder orderExpInfo = orderMapper.selectByPrimaryKey(orderId);
        Integer statusId = orderMapper.getOrderStatus(orderId);//todo 检测报错

        orderInfo.setExpName(orderExpInfo.getShipChannel());
        orderInfo.setExpCode(orderExpInfo.getShipChannel());
        orderInfo.setExpNo(orderExpInfo.getShipSn());




        String statusString = HandleOptionUtil.getStatusString(statusId);
        orderInfo.setOrderStatusText(HandleOptionUtil.getStatusString(statusId));
        HandleOption handleOption = HandleOptionUtil.getHandleOptionByStatus(statusId);

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getComments() == 0) {
            handleOption.setComment(false);
        }

        orderInfo.setHandleOption(handleOption);//utils转换
        orderDetail.setOrderInfo(orderInfo);//param1

        //param2
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(example);
        orderDetail.setOrderGoods(marketOrderGoods);//param2

        return orderDetail;
    }

    @Override
    public int delete(Integer orderId) {

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        int status = (int) marketOrder.getOrderStatus();
        if (status == 102 || status == 103 || status == 203) {

            orderMapper.deleteByOrderIdInLogic(orderId);
            orderGoodsMapper.deleteOrderGoodsByOrderIdInLogic(orderId);
            return 1;
        }
        return 0;
    }

    @Override
    public int cancel(Integer orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        int status = (int) marketOrder.getOrderStatus();
        if (status == 101) {
            orderMapper.orderCancelById(orderId);
            return 1;
        }
        return 0;
    }

    @Override
    public int confirm(Integer orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        int status = (int) marketOrder.getOrderStatus();
        if (status == 301) {
            //设置comments订单 查找订单里的商品数和
            int commentNum = orderGoodsMapper.countCommentByOrderId(orderId);
            orderMapper.orderConfrimById(orderId,commentNum);
            return 1;
        }
        return 0;
    }

    @Override
    public int refund(Integer orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        int status = (int) marketOrder.getOrderStatus();
        if (status == 201) {
            orderMapper.orderRefundById(orderId);
            return 1;
        }
        return 0;
    }

    @Override
    public void comment(CommentBO comment) {


        //通过orderId 查询order表 更新评论相关数据
        //通过GoodsId查询Goods信息 ? 在comment表插入相关内容
        Integer orderGoodsId = comment.getOrderGoodsId();
        MarketOrderGoods marketOrderGoods = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        Integer orderId = marketOrderGoods.getOrderId();
        Integer goodsId = marketOrderGoods.getGoodsId();
        //TODO:从shiro中拿到userID//已经修改
        Integer user =1;
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNicknameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        user = users.get(0).getId();

//        orderMapper.updateCommentInfoById(orderId);
        String content = comment.getContent();//评论内容
        Boolean hasPicture = comment.getHasPicture();//是否有图
        String[] picUrls = comment.getPicUrls();//图
        Integer star = comment.getStar();//评分
        commentMapper.addComment(content,hasPicture,picUrls,star,goodsId,user);

        //每评论完成一次 对Order的主表中comments数量-1;
        orderMapper.updateCommentNumById(orderId);
    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoods marketOrderGoods = orderGoodsMapper.orderGoods(orderId, goodsId);
        return marketOrderGoods;
    }

    @Override
    public SubmitVO submit(SubmitBO submitBO) {

        Integer cartId = submitBO.getCartId();//需要逻辑删除的购物车Id??
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNicknameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        Integer userId = users.get(0).getId();

        //得List<Cart>--->对应ordergoods表加入
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        criteria.andCheckedEqualTo(true);
        //传入userId 和 checked为1 和 delete 为0 的条件 查找List<cart>
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        //逻辑删除当前用户 购物车Check的项
        //逻辑删除Cart中刚刚添加的项目 --->delete=0,check=1,userId=参
        cartMapper.deleteCartInLogic(userId);


        //生成
        // 一个主订单 传出订单Id
        //todo:生成一个String orderSn
        String s = DateUtils.dateFormat(new Date());
        String orderSn = s+userId;
        //配置orderSn orderStatus consignee addtime
        String message = submitBO.getMessage();//该订单的备注信息
        Integer addressId = submitBO.getAddressId();//需要添加的 address信息 通过address表查询
        Address addressInfo = addressMapper.selectByPrimaryKey(addressId);
        //收货人
        String connsignee = addressInfo.getName();


        Integer provinceid = Integer.valueOf(addressInfo.getProvince());
        Integer cityid = Integer.valueOf(addressInfo.getCity());
        Integer countyid = Integer.valueOf(addressInfo.getCounty());
        String province = regionMapper.selectByPrimaryKey(provinceid).getName();
        String city = regionMapper.selectByPrimaryKey(cityid).getName();
        String county = regionMapper.selectByPrimaryKey(countyid).getName();

        //order地址
        String address =province+city+county;

        //ordertel
        String tel = addressInfo.getTel();

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUserId(userId);
        marketOrder.setOrderSn(orderSn);
        marketOrder.setConsignee(connsignee);
        marketOrder.setOrderStatus((short)101);
        marketOrder.setMobile(tel);
        marketOrder.setAddress(address);
        marketOrder.setMessage(message);
        marketOrder.setAddTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrder.setGoodsPrice(new BigDecimal(0));
        marketOrder.setActualPrice(new BigDecimal(0));
        marketOrder.setFreightPrice(new BigDecimal(0));
        marketOrder.setCouponPrice(new BigDecimal(0));
        marketOrder.setOrderPrice(new BigDecimal(0));
        marketOrder.setIntegralPrice(new BigDecimal(0));
        marketOrder.setGrouponPrice(new BigDecimal(0));
        marketOrder.setDeleted(false);

        //获取主订单OrderId 并完成基本订单信息
         orderMapper.insertSelective(marketOrder);
        Integer orderId = marketOrder.getId();


        //根据这个OrderId 插入List<Cart内容> 绑定OrderId
        //根据其他项目 为主Order订单赋值
        //开始对carts进行逻辑处理 遍历后加入 order_goods订单

        double doubleAllSum = 0;
        for (Cart cart : carts) {
            MarketOrderGoods orderGoods = new MarketOrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setProductId(cart.getProductId());
            orderGoods.setNumber(cart.getNumber());
            orderGoods.setPrice(cart.getPrice());
            //偷懒规格
            orderGoods.setSpecifications(cart.getSpecifications()[0]);
            orderGoods.setPicUrl(cart.getPicUrl());
            orderGoods.setGoodsSn(cart.getGoodsSn());
            orderGoods.setAddTime(new Date());
            orderGoods.setUpdateTime(new Date());
            orderGoods.setDeleted(false);

            orderGoodsMapper.insert(orderGoods);
            BigDecimal price = cart.getPrice();
            Short number = cart.getNumber();
            //计算该订单金额
            BigDecimal sum = price.multiply(BigDecimal.valueOf(number));
            double doubleSum = sum.doubleValue();
            doubleAllSum = doubleAllSum + doubleSum;
        }

        BigDecimal allSum = BigDecimal.valueOf(doubleAllSum);

        //计算到总金额后为order在
        Integer userCouponId = submitBO.getUserCouponId();//
        //逻辑判断满88原包邮
        if (doubleAllSum<88) {

            Coupon coupon = couponMapper.selectByPrimaryKey(userCouponId);
            BigDecimal discount = BigDecimal.valueOf(coupon.getDiscount());
            Double shipPricie = new Double(8);
            BigDecimal afterDiscount = BigDecimal.valueOf(allSum.doubleValue() + shipPricie);

            orderMapper.updatePriceAndShip(orderId,allSum,discount,afterDiscount);

            SubmitVO submitVO = new SubmitVO();
            submitVO.setOrderId(orderId);
            submitVO.setGrouponLinkId(null);
            return submitVO;


        }




        //todo:此处是优惠券简化版 只是减了金额 后续操作给wd
        //根据couponId计算减少
        Coupon coupon = couponMapper.selectByPrimaryKey(userCouponId);
        BigDecimal discount = BigDecimal.valueOf(coupon.getDiscount());
        //加运费

        BigDecimal afterDiscount = allSum.subtract(discount).add(BigDecimal.valueOf(8));

        orderMapper.updatePrice(orderId, allSum, discount, afterDiscount);

        CouponUser couponUser = new CouponUser();
        couponUser.setId(userCouponId);
        couponUser.setStatus((short) 1);
        couponUser.setOrderId(orderId);
        couponUser.setUsedTime(new Date());
        couponUserMapper.updateByPrimaryKeySelective(couponUser);

        SubmitVO submitVO = new SubmitVO();
        submitVO.setOrderId(orderId);
        submitVO.setGrouponLinkId(null);
        return submitVO;

    }


}
